package com.ycg.vue.component;

import com.ycg.vue.Exception.CustomException;
import com.ycg.vue.constant.Constant;
import com.ycg.vue.context.ThreadLocalContext;
import com.ycg.vue.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * @Description 拦截器
 * @Author jink
 * @Date 2024/1/9
 */
@Component
@Slf4j
public class Interceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    // 令牌过期时间
    private static final Long DELAYED_TIME = 3L;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        List<String> asList = Arrays.asList("/login", "/pageHomeImages", "/register", "/doc.html", "/v2", "/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**","/system/sendMail/**","/checkToken");
        String requestUrl = request.getRequestURI();
        log.info("请求的url为：{}", requestUrl);

        if (asList.stream().anyMatch(requestUrl::contains)) {
            log.info("{}-->已放行", requestUrl);
            return true;
        }

        String token = request.getHeader("token");
        log.info("从请求头中获取的令牌：{}", token);

        if (!StringUtils.hasLength(token)) {
            log.warn("Token不存在");
            throw new CustomException(401, Constant.TOKEN_ERROR);
        }

//        try {
//            if (redisTemplate.opsForValue().get(token) != null) {
                Claims claims = JwtUtils.parseJWT(token);
                ThreadLocalContext.setUserId(claims.get("id").toString());
                ThreadLocalContext.setUserName(claims.get("username").toString());
                ThreadLocalContext.setIp(claims.get("ip").toString());
//                redisTemplate.opsForValue().set(token, token, DELAYED_TIME, TimeUnit.HOURS);
                log.info("{}-->已放行", requestUrl);
//                log.info("用户：{}-->token已在线续期一小时", claims.get("id").toString());
                return true;
//            } else {
//                log.warn("token已过期");
//                throw new CustomException(401, Constant.TOKEN_TIMEOUT);
//            }
//        } catch (Exception e) {
//            log.error("token在线续期失败!");
//            e.printStackTrace();
//            throw new CustomException(401, Constant.USER_STATUS_ERROR);
//        }
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) throws Exception {
        ThreadLocalContext.removeUser();
    }
}